//
//  JPHUD.m
//  JPHUD
//
//  Created by carpenter.Li on 2017/8/14.
//  Copyright © 2017年 Carpenter. All rights reserved.
//

#import "JPHUD.h"
#import <Masonry/Masonry.h>
#import <pop/POP.h>

#define JPHUD_SUPVIEW [UIApplication sharedApplication].delegate.window
//[UIApplication sharedApplication].delegate.window

@interface JPProgressContentView()

/**
 左侧图标
 */
@property (nonatomic ,strong) UIImageView * stateImageView;

/**
 文本说明
 */
@property (nonatomic ,strong) UILabel * titleLabel;


@end

static CGFloat const VerticalClearance = 10;

@implementation JPProgressContentView

- (instancetype)initWithTitle:(NSString*)title mode:(JPProgressHUDMode)mode
{
    self = [super initWithFrame:CGRectZero];
    if (self) {
        
        self.backgroundColor = [UIColor darkGrayColor];
        
        self.layer.cornerRadius = 6;
        
        self.layer.masksToBounds = true;
        
        self.userInteractionEnabled = false;
        
        self.mode = mode;
        
        
        self.stateImageView = [UIImageView new];
        [self addSubview:self.stateImageView];
        
        self.titleLabel = [UILabel new];
        self.titleLabel.textColor = [UIColor whiteColor];
        self.titleLabel.font = [UIFont systemFontOfSize:15];
        self.titleLabel.numberOfLines = 0;
        self.titleLabel.text = title;
        [self addSubview:self.titleLabel];
        
        [self.stateImageView mas_makeConstraints:^(MASConstraintMaker *make) {
            make.centerY.mas_equalTo(0);
            make.left.mas_equalTo(14);
            make.width.height.mas_equalTo(26);
        }];
        [self.titleLabel mas_makeConstraints:^(MASConstraintMaker *make) {
            make.top.mas_equalTo(VerticalClearance);
            make.right.mas_equalTo(-14);
            make.left.mas_equalTo(self.stateImageView.mas_right).offset(5);
            make.bottom.mas_equalTo(-VerticalClearance);
            make.height.mas_greaterThanOrEqualTo(25);
        }];
        
        switch ( mode) {
            case JPProgressHUDMode_Text:
            {
                self.stateImageView.image = [UIImage new];
                self.stateImageView.hidden = true;
                [self.stateImageView mas_remakeConstraints:^(MASConstraintMaker *make) {
                    make.centerY.mas_equalTo(0);
                    make.left.mas_equalTo(5);
                    make.width.height.mas_equalTo(0);
                }];
                
                self.titleLabel.textAlignment = NSTextAlignmentCenter;
                [self.titleLabel mas_remakeConstraints:^(MASConstraintMaker *make) {
                    make.edges.mas_equalTo(UIEdgeInsetsMake(VerticalClearance, 15, VerticalClearance, 15));
                    make.height.mas_greaterThanOrEqualTo(25);
                    make.width.mas_greaterThanOrEqualTo(100);
                }];
            }
                break;
            case JPProgressHUDMode_Progress:
            {
                self.stateImageView.image = [self imageNamedFromJPHUDBundle:@"hud_progress"];
                CABasicAnimation *caAnimation = [CABasicAnimation animationWithKeyPath:@"transform.rotation.z"];
                caAnimation.toValue  = @(2 * M_PI);
                caAnimation.duration = 1.0;
                caAnimation.repeatCount = MAXFLOAT;
                [self.stateImageView.layer addAnimation:caAnimation forKey:nil];
                
            }
                break;
            case JPProgressHUDMode_Error:
            {
                self.stateImageView.image = [self imageNamedFromJPHUDBundle:@"hud_error"];
            }
                break;
            case JPProgressHUDMode_Success:
            {
                self.stateImageView.image = [self imageNamedFromJPHUDBundle:@"hud_success"];
            }
                break;
            case JPProgressHUDMode_Custom:
            {
                self.stateImageView.image = [self imageNamedFromJPHUDBundle:@""];//FIXME: - 预留
            }
                break;
            default:
                break;
        }
        
    }
    return self;
}


-(UIImage *)imageNamedFromJPHUDBundle:(NSString*)name{
    
    NSBundle *bundle = [NSBundle bundleForClass:[JPHUD class]];
    NSURL *url = [bundle URLForResource:@"JPHUD" withExtension:@"bundle"];
    bundle = [NSBundle bundleWithURL:url];
    
    name = [name stringByAppendingString:@"@2x"];
    NSString *imagePath = [bundle pathForResource:name ofType:@"png"];
    UIImage *image = [UIImage imageWithContentsOfFile:imagePath];
    if (!image) {
        // 兼容业务方自己设置图片的方式
        name = [name stringByReplacingOccurrencesOfString:@"@2x" withString:@""];
        image = [UIImage imageNamed:name];
    }
    
    return image?:[UIImage new];
    
}

@end

@implementation JPProgressBackgroundView


-(instancetype)initWithStyle:(JPProgressHUDBackgroundStyle)style{
    
    if (self = [super initWithFrame:CGRectZero]) {
        
        self.userInteractionEnabled = false;
        
        self.backgroundStyle = style;
        
    }
    return self;
}
-(void)setBackgroundStyle:(JPProgressHUDBackgroundStyle)backgroundStyle{
    _backgroundStyle =backgroundStyle;
    switch (backgroundStyle) {
        case JPProgressHUDBackgroundStyle_gray:
            self.backgroundColor = [[UIColor blackColor] colorWithAlphaComponent:0.25];
            break;
        default:
            self.backgroundColor = [[UIColor blackColor] colorWithAlphaComponent:0.01];
            break;
    }
}

@end

static CGFloat const ContinuousTimeInterval = 1.5;//视图展示时间

@implementation JPHUD

-(instancetype)initWithView:(UIView*)view title:(NSString*)title continuousTimeInterval:(NSTimeInterval)continuousTimeInterval contentViewMode:(JPProgressHUDMode)contentViewMode showType:(JPProgressHUDShowType)showType backgroundStyle:(JPProgressHUDBackgroundStyle)backgroundStyle{
    
    if (self = [super initWithFrame:view.frame]) {
        
        self.backgroundView = [[JPProgressBackgroundView alloc] initWithStyle:backgroundStyle];
        [self addSubview:self.backgroundView];
        [self.backgroundView mas_makeConstraints:^(MASConstraintMaker *make) {
            make.edges.mas_equalTo(0);
        }];
        
        self.contentView = [[JPProgressContentView alloc] initWithTitle:title mode:contentViewMode];
        [self addSubview:self.contentView];
        
        if (showType == JPProgressHUDShowType_Center) {
            [self.contentView mas_makeConstraints:^(MASConstraintMaker *make) {
                make.center.mas_equalTo(0);
                make.width.mas_lessThanOrEqualTo(view.frame.size.width * 0.7);
            }];
        }else{
            [self.contentView mas_makeConstraints:^(MASConstraintMaker *make) {
                make.centerX.mas_equalTo(0);
                make.bottom.mas_equalTo(view.frame.size.height * 0.2 * -1);
                make.width.mas_lessThanOrEqualTo(view.frame.size.width * 0.85);
            }];
        }
        
        
        if (contentViewMode != JPProgressHUDMode_Progress) {
            
            dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(continuousTimeInterval * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
                
                [JPHUD hideHUDInView:view animated:true];
                
            });
            
        }
        
        
    }
    return self;
}

+ (instancetype)sharedHUDView:(UIView*)view title:(NSString*)title continuousTimeInterval:(NSTimeInterval)continuousTimeInterval contentViewMode:(JPProgressHUDMode)contentViewMode showType:(JPProgressHUDShowType)showType backgroundStyle:(JPProgressHUDBackgroundStyle)backgroundStyle{
    
    [JPHUD hideHUDForAnimated:false];
    
    if (!view) {
        view = JPHUD_SUPVIEW;
    }
    if (title == nil) {
        if (contentViewMode == JPProgressHUDMode_Text) {
            title = @"我也不知道应该说点什么";
        }else if (contentViewMode == JPProgressHUDMode_Success) {
            title = @"干的漂亮!";
        }if (contentViewMode == JPProgressHUDMode_Error) {
            title = @"出错了!";
        }else if (contentViewMode == JPProgressHUDMode_Progress) {
            title = @"加载中...";
        }
    }
    
    JPHUD * hud = [[JPHUD alloc] initWithView:view title:title continuousTimeInterval:continuousTimeInterval contentViewMode:contentViewMode showType:showType backgroundStyle:backgroundStyle];
    [view addSubview:hud];
    [view bringSubviewToFront:hud];
    return hud;
    
}
+ (instancetype) showText:(NSString*)title view:(UIView*)view{
    
    return  [JPHUD sharedHUDView:view title:title continuousTimeInterval:ContinuousTimeInterval contentViewMode:JPProgressHUDMode_Text showType:JPProgressHUDShowType_Center backgroundStyle:JPProgressHUDBackgroundStyle_Clear];
    
}
+ (instancetype) showText:(NSString*)title{
    return [JPHUD showText:title view:nil];
}

+ (instancetype) showProgress:(NSString*)title view:(UIView*)view{
    
    return  [JPHUD sharedHUDView:view title:title continuousTimeInterval:ContinuousTimeInterval contentViewMode:JPProgressHUDMode_Progress showType:JPProgressHUDShowType_Center backgroundStyle:JPProgressHUDBackgroundStyle_gray];
    
}
+ (instancetype) showProgress:(NSString*)title{
    return [JPHUD showProgress:title view:nil];
}
+ (instancetype) showProgress{
    return  [JPHUD showProgress:nil];
}

+ (instancetype) showSuccess:(NSString*)title view:(UIView*)view{
    
    return  [JPHUD sharedHUDView:view title:title continuousTimeInterval:ContinuousTimeInterval contentViewMode:JPProgressHUDMode_Success showType:JPProgressHUDShowType_Center backgroundStyle:JPProgressHUDBackgroundStyle_Clear];
    
}
+ (instancetype) showSuccess:(NSString*)title{
    return [JPHUD showSuccess:title view:nil];
}
+ (instancetype) showSuccess{
    return  [JPHUD showSuccess:nil];
}

+ (instancetype) showError:(NSString*)title view:(UIView*)view{
    
    return  [JPHUD sharedHUDView:view title:title continuousTimeInterval:ContinuousTimeInterval contentViewMode:JPProgressHUDMode_Error showType:JPProgressHUDShowType_Center backgroundStyle:JPProgressHUDBackgroundStyle_Clear];
    
}
+ (instancetype) showError:(NSString*)title{
    return [JPHUD showError:title view:nil];
}
+ (instancetype) showError{
    return  [JPHUD showError:nil];
}
+ (void)hideHUD{
    [JPHUD hideHUDForAnimated:true];
}
+ (void)hideHUDForAnimated:(BOOL)animated{
    [JPHUD hideHUDInView:JPHUD_SUPVIEW animated:animated];
}
+ (void)hideHUDInView:(UIView*)view animated:(BOOL)animated{
    
    for (JPHUD * subview in view.subviews) {
        
        if ([subview isMemberOfClass:[JPHUD class]]) {
            
            if (animated) {
                POPBasicAnimation * animate = [POPBasicAnimation animationWithPropertyNamed:kPOPViewScaleXY];
                animate.fromValue = [NSValue valueWithCGPoint:CGPointMake(1, 1)];
                animate.toValue = [NSValue valueWithCGPoint:CGPointMake(0.1, 0.05)];
                animate.duration = 0.3;
                [subview.contentView pop_addAnimation:animate forKey:@"remove"];
                
                animate.completionBlock = ^(POPAnimation *anim, BOOL finished) {
 
                    if (subview.hudHideComplete) {
                        subview.hudHideComplete();
                    }
                    
                    [subview removeFromSuperview];
                };
                
            }else{
                
                if (subview.hudHideComplete) {
                    subview.hudHideComplete();
                }
                
                [subview removeFromSuperview];
            }
        }
    }
    return;
    
    
}

@end

 
